package com.learning.thread.juc.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * ClassName: ReentrantLockTest
 * Description: 重入锁 ReentrantLock
 * Date: 2016/11/26 17:45
 *
 * @author SAM SHO
 * @version V1.0
 */
public class ReentrantLockTest {


    void test1() {
        DataObject data = new DataObject();
        new Thread(new InThreadTask(data), "thread0").start();
        new Thread(new InThreadTask(data), "thread1").start();
    }

    /**
     * 任务线程
     */
    class InThreadTask implements Runnable {

        private DataObject data;

        public InThreadTask(DataObject data) {
            this.data = data;
        }

        @Override
        public void run() {
            data.get("abcdefghijklmnopqrstuvwxyz");
        }
    }

    /**
     * 业务对象
     */
    class DataObject {

        /**
         * 定义锁对象
         */
        ReentrantLock lock = new ReentrantLock();

        /**
         * Lock实现
         *
         * @param name
         */
        void get(String name) {

            int length = name.length();
            try {
                // 获得锁，如果锁已经占用，则等待
                lock.lock();
                System.out.println("锁是否公平： " + lock.isFair());
                System.out.println("getHoldCount: " + lock.getHoldCount());
                System.out.println("getQueueLength: " + lock.getQueueLength());
                for (int i = 0; i < length; i++) {
                    System.out.print(name.charAt(i));
                }
                System.out.println();
            } finally {
                // 需要手动解锁，一定要注意
                lock.unlock();
            }
        }
    }
}
